# -*- coding: utf-8 -*-
import webapp2
import exceptions

from footballmodels import Team, Player
from webapp2 import uri_for

NUM_PLAYERS = 11

class ViewTeams(webapp2.RequestHandler):
    def get(self, *args, **kwargs):
        team_query = Team.query().order(Team.teamname)
        self.response.write('<html><body>')
        if team_query.count() > 0:
            self.response.write('<table border="1"><tr>')
            for team in team_query:
                self.response.write('<th>%s</th>' % (team.teamname))
            self.response.write('</tr><tr>')
            for teamkey in team_query.iter(keys_only=True):
                self.response.write('<td><ul>')
                players_query = Player.query(ancestor=teamkey).order(-Player.iscap, Player.plname)
                for player in players_query: 
                    self.response.write('<li>%s</li>' % (player.plname))
                self.response.write('</ul></td>')
            self.response.write('</tr><tr>')
            for teamkey in team_query.iter(keys_only=True):
                self.response.write("""\n
                <td><form action="%s" method="post"><input type="submit" value="Редактировать">
                <input type="hidden" name="id" value="%s"></form></td>""" % (uri_for('edit'), teamkey.id()))
            self.response.write('\n</tr></table>')
        self.response.write("""\n
                <form action="%s" method="post">
                <input type="submit" value="Добавить команду"></form>\n</body></html>""" % (uri_for('edit')))

class EditTeam(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(EditTeam, self).__init__(*args, **kwargs)

    def post(self, *args, **kwargs):
        self.response.write('<html><body>\n')
        if self.request.get('id') == '':
            self.response.write('<form action="%s" method="post">\n' % (uri_for('applyedit')))
            self.response.write('<input type="hidden" name="new" value="yes">\n')
            self.response.write('<label for="teamname">Название команды: </label><input name="teamname" type="text"><br>\n')
            self.response.write('<label for="captain">Капитан:</label><input name="captain" type="text"><br>\n')
            for i in range(1, NUM_PLAYERS):
                self.response.write('<label for="pl%dname">Игрок %d:</label><input name="pl%dname" type="text"><br>\n' % (i, i, i))
            self.response.write('<input type="submit" value="ОК">\n</form>\n')
        else:
            team = Team.get_by_id(int(self.request.get('id')))
            teamkey = team.key
            players = [player for player in Player.query(ancestor=teamkey).order(-Player.iscap, Player.plname)]
            plcount = len(players)
            self.response.write('<form action="%s" method="post">\n' % (uri_for('applyedit')))
            self.response.write('<input type="hidden" name="id" value="%s">\n' % (self.request.get('id')))
            self.response.write(u'<label for="teamname">Название команды:</label><input name="teamname" type="text" value="%s"><br>\n' % (team.teamname))
            self.response.write(u'<label for="captain">Капитан:</label><input name="captain" type="text" value="%s"><br>\n' % (players[0].plname))
            for i in range(1, plcount):
                self.response.write(u'<label for="pl%dname">Игрок %d:</label><input name="pl%dname" type="text" value="%s"><br>\n' % (i, i, i, players[i].plname))
            for i in range(plcount, NUM_PLAYERS):
                self.response.write('<label for="pl%dname">Игрок %d:</label><input name="pl%dname" type="text"><br>\n' % (i, i, i))
            self.response.write('<input type="submit" value="ОК">\n</form>\n')
            self.response.write(u"""<form action="%s" method="post">
                <input type="submit" value="Удалить команду">
                <input type="hidden" name="delete" value="yes">
                <input type="hidden" name="id" value="%s"></form>\n""" % (uri_for('applyedit'), self.request.get('id')))
        self.response.write("""<form action="%s" method="post">
            <input type="submit" value="Отмена"><input type="hidden" name="cancel" value="yes">
            </form>\n</body></html>""" % (uri_for('applyedit')))

class ApplyEdit(webapp2.RequestHandler):
    def __init__(self, *args, **kwargs):
        super(ApplyEdit, self).__init__(*args, **kwargs)

    def post(self, *args, **kwargs):
        if self.request.get('cancel') == 'yes':
            self.redirect(uri_for('show'))
            return
        if self.request.get('new') == 'yes':
            team = Team(teamname=self.request.get('teamname'))
            teamkey = team.put()
            cap = Player(plname=self.request.get('captain'), iscap=True, parent=teamkey)
            cap.put()
            for i in range(1, NUM_PLAYERS):
                plname = self.request.get('pl%dname' % (i))
                if plname == '':
                    continue
                player = Player(plname=plname, parent=teamkey)
                player.put()
        else:
            team = Team.get_by_id(int(self.request.get('id')))
            teamkey = team.key
            player_query = Player.query(ancestor=teamkey).order(-Player.iscap, Player.plname)
            for playerkey in player_query.iter(keys_only=True):
                playerkey.delete()
            if self.request.get('delete') == 'yes':
                teamkey.delete()
                self.redirect(uri_for('show'))
                return
            team.teamname = self.request.get('teamname')
            team.put()
            cap = Player(plname=self.request.get('captain'), iscap=True, parent=teamkey)
            cap.put()
            for i in range(1, NUM_PLAYERS):
                plname = self.request.get('pl%dname' % (i))
                if plname == '':
                    continue
                player = Player(plname=plname, parent=teamkey)
                player.put()
        self.redirect(uri_for('show'))

